package com.xuxu.blog.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xuxu.blog.entity.UserEntity;
import com.xuxu.blog.utils.IpUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuxu.common.utils.PageUtils;
import com.xuxu.common.utils.Query;

import com.xuxu.blog.dao.InfoDao;
import com.xuxu.blog.entity.InfoEntity;
import com.xuxu.blog.service.InfoService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Service("infoService")
public class InfoServiceImpl extends ServiceImpl<InfoDao, InfoEntity> implements InfoService {
    @Resource
    private InfoDao infoDao;
    @Resource
    private InfoServiceImpl infoService;
    @Resource
    private HttpServletRequest request;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<InfoEntity> page = this.page(
                new Query<InfoEntity>().getPage(params),
                new QueryWrapper<InfoEntity>()
        );
        return new PageUtils(page);
    }


    public InfoEntity saveCurrentInfo(UserEntity userEntity) {
        // 存储用户登录信息
        InfoEntity infoEntity = new InfoEntity();
        String ipAddress = IpUtils.getIpAddress(request);
        String ipSource = IpUtils.getIpSource(ipAddress);
        String type = IpUtils.getUserAgent(request).toString();
        infoEntity.setType(type);
        infoEntity.setUsername(userEntity.getUsername());
        infoEntity.setEnable(1);
        infoEntity.setIp(ipAddress);  // ip
        infoEntity.setAddr(ipSource);  // 城市名
        infoEntity.setTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));// 创建时间
        UpdateWrapper<InfoEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("username", userEntity.getUsername());
        infoService.saveOrUpdate(infoEntity,wrapper);
        return infoEntity;
    }
}